import { computed, ref } from 'vue'
import { defineStore } from 'pinia'

export const useParamsStore = defineStore('params', () => {
  const param = ref({
    ueId: 'defaultData',
    type: 1,
    addressId: '020'
  })
  const diyUList = ref([])
  function setDiyUList (newList = []) {
    diyUList.value = newList
  }
  // 不传就改为空
  function setParamsAll (newParams = {}) {
    param.value = {
      ueId: newParams?.ueId + '' === '1' ? 'defaultData' : (newParams?.ueId ?? 'defaultData'),
      type: newParams?.type ?? 1,
      addressId: newParams?.addressId ?? '',
    }
  }
  // 不传就不改
  function setParams (newParams) {
    param.value = {
      ...param.value,
      ...newParams
    }
  }

  const czModel = ref(false)
  function setCzModel (hasModel = false) {
    czModel.value = hasModel
  }

  const treeData = ref([])
  function setTreeData (tree = []) {
    treeData.value = tree
  }
  const ueId2AddressId = computed(() => {
    function dgui (list = [], getitem) {
      list.forEach(item => {
        getitem(item)
        if (item?.children?.length > 0) {
          dgui(item.children, getitem)
        }
      })
    }
    const map = {}
    dgui(treeData.value, item => {
      map[item.ueId] = item.id
    })
    return map
  })
  function getAddressFromUeId (ueId) {
    return ueId2AddressId.value[ueId]
  }
  return {
    czModel, setCzModel, param, setParamsAll, setParams, treeData, setTreeData, getAddressFromUeId,
    diyUList,
    setDiyUList
  }
})
